﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using it_security_project.App_Code.BusinessLogicLayer;
using it_security_project.App_Code;
using System.Text.RegularExpressions;
using System.Net.Mail;

namespace it_security_project
{
    public partial class Profile : System.Web.UI.Page
    {
        public new Site site { get { return base.Master as Site; } }

        private string SuccessGroup = "successmessage";
        private string ErrorGroup = "errormessage";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["deleteThread"] != null)
            {
                Service service = new Service();
                //security check               
                var member = site.LoginWithSession();
                if (member != null)
                {
                    if(member.Role == Roles.Member) 
                    {
                        DeleteThreadAsMember(service);
                    }
                    else if (member.Role == Roles.Admin || member.Role == Roles.Moderator)
                    {
                        DeleteThreadAsAdmin(service);
                    }
                    
                }                
            }
        }

        private void DeleteThreadAsAdmin(Service service)
        {
            try
            {
                int navigatedThreadID = int.Parse(Request.QueryString["deleteThread"]);

                service.DeleteThread(navigatedThreadID);

                
                site.ChangeCustomMessage("The thread has been deleted!", MessageType.Success);
                //PageExtensions.AddErrorMessage(this, "The thread has been deleted!", SuccessGroup);
            }
            catch (Exception)
            {
                site.ChangeCustomMessage("An error has occured!", MessageType.Error);
                //PageExtensions.AddErrorMessage(this, "An error has occured!", ErrorGroup);
            }
            
        }

        private void DeleteThreadAsMember(Service service)
        {
            try
            {
                var threads = service.GetThreadsByUsername(site.GetSessionUsername());
                var thisthread = service.GetThreadById(int.Parse(Request.QueryString["deleteThread"]));
                var ids = new List<int>();
                for (int i = 0; i < threads.Count; i++)
                {
                    ids.Add(threads[i].ThreadID);
                }
                if (ids.Contains(thisthread.ThreadID))
                {
                    int navigatedThreadID = int.Parse(Request.QueryString["deleteThread"]);

                    service.DeleteThread(navigatedThreadID);

                    site.ChangeCustomMessage("The thread has been deleted!", MessageType.Success);
                    //PageExtensions.AddErrorMessage(this, "The thread has been deleted!", SuccessGroup);
                }
            }
            catch (Exception)
            {
                site.ChangeCustomMessage("An error has occured!", MessageType.Error);
                //PageExtensions.AddErrorMessage(this, "An error has occured!", ErrorGroup);
            }   
            
        }

        protected override void OnInit(EventArgs e)
        {
            Member member = site.LoginWithSession();

            if (member == null) // User is NOT logged in
            {
                Response.Redirect("~/Default.aspx");
            }

            if (member.Role == Roles.Moderator || member.Role == Roles.Admin)
            {
                threadsheader.Text = "All Threads";
                ProfileObjectDataSource.SelectMethod = "GetThreads";
                Parameter p = ProfileObjectDataSource.SelectParameters["username"];
                ProfileObjectDataSource.SelectParameters.Remove(p);
            }

        }

        protected void ButtonChangeInformation_Click(object sender, EventArgs e)
        {
            var password = TextboxPassword.Text;
            var passwordrep = TextboxRepeatPassword.Text;
            var email = TextboxEmail.Text;
            var emailrep = TextboxEmailRepeat.Text;

            // Want to change password ONLY
            if (!string.IsNullOrEmpty(password) && !string.IsNullOrEmpty(passwordrep) && string.IsNullOrEmpty(email) && string.IsNullOrEmpty(emailrep))
            {
                if (password.Length <= 50)
                {
                    ChangePassword(password, passwordrep);
                }
                else
                {
                    site.ChangeCustomMessage("Password toooooooo long",MessageType.Error);
                }
            }
            // Want to change both password AND email
            else if (!string.IsNullOrEmpty(password) && !string.IsNullOrEmpty(passwordrep) && !string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(emailrep))
            {
                try
                {
                    if (password.Length <= 50)
                    {
                        if (email.Length <= 100)
	                    {
		                    ChangePassword(password, passwordrep);
                            ChangeEmail(email, emailrep);
                            site.ChangeCustomMessage("It actually worked! Your Email AND password has been changed :D", MessageType.Success);  
	                    }
                        else
                        {
                            site.ChangeCustomMessage("Email toooooooo looong",MessageType.Error);
                        }
                    }
                    else
                    {
                        site.ChangeCustomMessage("Password toooooooo long", MessageType.Error);
                    }
                    
                }
                catch (Exception)
                {
                    // Handeled elsewhere
                }
                
            }
            // Only change Email
            else if (!string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(emailrep) && string.IsNullOrEmpty(password) && string.IsNullOrEmpty(passwordrep))
            {
                ChangeEmail(email, emailrep);
            }
        }

        private void ChangeEmail(string email, string emailrep)
        {
            // Email match
            if (email == emailrep)
            {
                Service s = new Service();
                Member m = site.LoginWithSession();
                if (m != null)
                {
                    try
                    {
                        try
                        {
                            MailAddress mail = new MailAddress(email);
                            m.EmailAdress = email;
                            try
                            {
                                s.ChangeEmail(m.Username, email);
                                site.SetViewstate(m);
                                site.ChangeCustomMessage("It actually worked! Your Email has been changed :D", MessageType.Success);
                            }
                            catch (Exception)
                            {
                                site.ChangeCustomMessage("An error occured when changing your email, please contact Ape nr 1324299973 for assistance.", MessageType.Error);
                            }
                        }
                        catch
                        {
                            site.ChangeCustomMessage("Email was wrong, concentration!",MessageType.Error);
                        }
                    }
                    catch (Exception)
                    {
                        site.ChangeCustomMessage("Email is WRONG!",MessageType.Error);
                    }
                }
                else
                {
                    site.ChangeCustomMessage("Oh shit, session is compromised!", MessageType.Error);
                    site.ClearSession();
                }
            }
            else
            {
                site.ChangeCustomMessage("Email doesn´t match",MessageType.Error);
            }
        }

        private void ChangePassword(string password, string passwordrep)
        {
            // Password match
            if (password == passwordrep)
            {
                Service s = new Service();
                Member m = site.LoginWithSession();
                if (m != null)
                {
                    try
                    {
                        s.ChangePassword(m.Username, password);
                        m.Password = Cryptation.HashPassword(password);
                        site.SetViewstate(m);
                        site.ChangeCustomMessage("It actually worked! Your password has been changed :D",MessageType.Success);
                    }
                    catch (Exception)
                    {
                        site.ChangeCustomMessage("An error occured when changing your password, please contact Ape nr 132423235 for assistance.", MessageType.Error);
                    }
                }
                else
                {
                    site.ChangeCustomMessage("Oh shit, session is compromised!",MessageType.Error);
                    site.ClearSession();
                }
            }
            else
            {
                site.ChangeCustomMessage("Password don´t match.", MessageType.Error);
            }
        }
    }
}